import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:mmkv/mmkv.dart';
import 'package:seedfour/app/models/transfer_user_entity.dart';

import '../../../toolkit/utils/encrypt_utils.dart';
import '../../services/api_service.dart';

class TransferLogic extends GetxController {
  final mmkv = MMKV.defaultMMKV();
  final apiService = Get.find<ApiService>();

  var balance = '0.00'.obs;
  var transferUsers = <TransferUserEntity>[].obs;
  var selectedUser = TransferUserEntity().obs;

  final isAllocOrder = false.obs;
  var allocOrderId = ''.obs;

  late GlobalKey<FormState> formKey;

  // 转账对象搜索输入框
  late TextEditingController searchController;

  // 转账金额输入框控制器
  late TextEditingController amountController;

  // 转账附言输入框控制器
  late TextEditingController remarkController;

  // 支付密码输入框控制器
  late TextEditingController payPasswordController;

  String _payKey = '';

  @override
  void onInit() {
    super.onInit();
    formKey = GlobalKey<FormState>();
    TransferParams params = Get.arguments;
    // balance.value = Get.arguments;
    balance.value = params.balance;
    isAllocOrder.value = params.isAllocOrder;
    allocOrderId.value = params.allocOrderId!;

    searchController = TextEditingController();
    amountController = TextEditingController();
    remarkController = TextEditingController();
    payPasswordController = TextEditingController();

    _getTransferUsers();
  }

  void initPasswordController() {
    payPasswordController = TextEditingController();
  }

  // 转账
  void submitTransfer() {
    if (formKey.currentState!.validate()) {
      EasyLoading.show(status: '转账中...', dismissOnTap: true);

      _getPayKey();
    }
  }

  void _getPayKey() {
    apiService.getPayKey(onError: (e) {
      EasyLoading.showError(e.toString());
      return true;
    }).then((value) {
      if (value != null && value.isNotEmpty) {
        _payKey = value;

        _transfer();
      } else {
        EasyLoading.showError('请求失败');
      }
    });
  }

  void _transfer() {
    String password = rsaEncrypt(_payKey, payPasswordController.text);
    //20250725 增加专款的转账
    if(!isAllocOrder.value) {
      apiService
          .transfer(
        amountController.text,
        password,
        selectedUser.value.uid!,
        remark: remarkController.text,
      )
          .then((value) {
        if (value == null) {
          EasyLoading.showError('网络错误，请稍后重试！');
          return;
        }
        if (value.value['success'] == true) {
          EasyLoading.showSuccess('转账成功');
          Get.back(result: true);
        } else {
          EasyLoading.showError(value.value['error']['message']);
        }
      });
    }
    else{
      apiService
          .allocOrderTransfer(
        allocOrderId.value,
        amountController.text,
        selectedUser.value.uid!,
        password,
        remark: remarkController.text
      )
          .then((value) {
        if (value == null) {
          EasyLoading.showError('网络错误，请稍后重试！');
          return;
        }
        if (value.value['success'] == true) {
          EasyLoading.showSuccess('转账成功');
          Get.back(result: true);
        } else {
          EasyLoading.showError(value.value['error']['message']);
        }
      });
    }
  }

  // 获取转账用户列表
  void _getTransferUsers() {
    apiService.getTransferUserList().then((users) => {
          if (users != null)
            {
              transferUsers.value = users.data ?? [],
            }
        });
  }

  @override
  void onClose() {
    amountController.dispose();
    remarkController.dispose();
    super.onClose();
  }
}

class TransferParams {
  String balance;
  bool isAllocOrder = false;
  String? allocOrderId;

  TransferParams({  required this.balance, this.allocOrderId = '', this.isAllocOrder = false});
}